<div class="layui-tab layui-tab-brief">
    <ul class="layui-tab-title">
        <li class="layui-this">部门管理</li>
        <li>组织架构图</li>
    </ul>
    <div class="layui-tab-content" style="height: 100px;">
        <div class="layui-tab-item layui-show">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-card-header">
                        <a id="add" shiro:hasAnyPermissions="admin,department:all,department:add" class="layui-btn layui-btn-xs">
                            <i class="layui-icon"></i>
                            <span>新增</span>
                        </a>
                        <a href="javascript:;" class="layui-btn layui-btn-xs layui-btn-primary" id="search_hash">
                            <i class="layui-icon">&#xe615;</i>
                        </a>
                    </div>
                    <table class="layui-table" id="myTable" lay-filter="tools"></table>
                    <script type="text/html" id="operation">
                        <button shiro:hasAnyPermissions="admin,department:all,department:update" class="layui-btn layui-btn-xs" lay-event="edit">编辑</button>
                        <button shiro:hasAnyPermissions="admin,department:all,department:delete" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
                    </script>
                </div>
            </div>
        </div>
        <div class="layui-tab-item" style="padding: 10px;">
            <div id='jOrgChart'></div>
        </div>
    </div>
</div>

<script th:src="@{'/js/jquery.jOrgChart.js'}"></script>
<script type="text/html" id="search_tpl_hash">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">部门编号</label>
            <div class=layui-input-lump>
                <input type="text" name="id" placeholder="请输入部门编号.." autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">部门名称</label>
            <div class=layui-input-lump>
                <input type="text" name="name" placeholder="请输入部门名称.." autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-lump">
                <button class="layui-btn" lay-submit lay-filter="formDemo_hash">搜索</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</script>

<script>
    var treeGrid = null;
    layui.use(['jquery', 'sidebar', 'form' , 'treeGrid'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            table = layui.table,
            sidebar = layui.sidebar,
            form = layui.form;
            treeGrid = layui.treeGrid;

        //监听新增事件
        $('#add').on('click', function(){
            var index = layer.open({
                type: 2
                ,content: '/department/toAddPage'
                ,area: ['500px', '450px']
                ,btnAlign: 'c'
                ,shade: 0.8
                ,title: '新增部门'
                ,maxmin: true
                ,btn: ['确认', '取消']
                ,yes: function(){
                    var body = layer.getChildFrame('body', index);
                    add(layer,body);
                }
            });
        });

        //表格渲染
        treeGrid.render({
            id:"ID"
            ,elem: '#myTable'
            ,idField:'id'
            ,url:'/department/getDepartmentsInfo'
            ,cellMinWidth: 100
            ,treeId:'id'//树形id字段名称
            ,treeUpId:'pid'//树形父id字段名称
            ,treeShowName:'name'//以树形式显示的字段
            ,height:'full-140'
            ,isFilter:false
            ,iconOpen:false//是否显示图标【默认显示】
            ,isOpenDefault:true//节点默认是展开还是折叠【默认展开】
            ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,cols: [
                [
                    {field:'id',align:'center', width:70,  title: '编号'}
                    ,{field:'name',  title: '部门名称'}
                    ,{field:'createTime',  title: '创建日期'}
                    ,{field:'operation',align:'center', width:150, toolbar: '#operation', title: '操作'}
                ]
            ]
            ,page: false
        });

        //监听搜索事件
        $('#search_hash').on('click', function () {
            var that = this;
            sidebar.render({
                elem: that,
                content: $('#search_tpl_hash').html(),
                title: '搜索',
                shade: true,
                width: '450px', //可以设置百分比和px
                done: function () {
                    form.render();
                    //监听提交
                    form.on('submit(formDemo_hash)', function (data) {
                        treeGrid.query('ID', {
                            where: {
                                id: $('input[name="id"]').val(),
                                name: $('input[name="name"]').val(),
                            }
                            ,page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                        return false;
                    });
                }
            });
        });

        //监听修改按钮
        treeGrid.on('tool(tools)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                // 编辑
                var index = layer.open({
                    type: 2
                    ,content: '/department/toUpdatePage?id='+data.id
                    ,area: ['500px', '450px']
                    ,btnAlign: 'c'
                    ,shade: 0.8
                    ,title: '编辑部门'
                    ,maxmin: true
                    ,btn: ['确认', '取消']
                    ,yes: function(){
                        var body = layer.getChildFrame('body', index);
                        update(layer,body);
                    }
                });
                //监听删除事件
            } else if(obj.event === 'del'){
                layer.confirm("你确定删除数据吗？如果存在下级节点<br/>则一并删除，此操作不能撤销！", {icon: 3 ,btnAlign: 'c', title:'提示'},
                    function(index){//确定回调
                        // 写删除方法
                        $.ajax({
                            url: "/department/delete?id="+data.id,
                            type: "DELETE",
                            success: function(data){
                                if (data.code == 200) {
                                    layer.close(index);
                                    spop({
                                        template: '删除成功',
                                        style: 'success',
                                        autoclose: 2000
                                    });
                                    treeGrid.reload('ID', {
                                        where: {}
                                        ,page: {
                                            curr: 1
                                        }
                                    });
                                    jOrgChart()
                                } else {
                                    layer.close(index);
                                    spop({
                                        template: data.msg,
                                        style: 'error',
                                        autoclose: 2000
                                    });
                                }
                            }
                        });
                        layer.close(index);
                    },function (index) {//取消回调
                        layer.close(index);
                    }
                );
            }
        });
    });

    /**
     * 新增
     * @param layer
     * @param body
     */
    function add(layer,body) {
        var name = body.contents().find("input[name=\"name\"]").val();
        var pid = body.contents().find("#tree").val();
        var roles = body.contents().find("input[name=\"role\"]").val();

        $.ajax({
            url: "/department/insert?roles="+roles,
            contentType: "application/json",
            type: "POST",
            data:JSON.stringify({
                name:name,
                pid:pid
            }),
            dataType: "json",
            success: function(data){
                if(data.code==200){
                    //同步更新表格和缓存对应的值
                    layui.use(['jquery', 'layer'], function (){
                        layer.closeAll();

                        spop({
                            template: '添加成功',
                            style: 'success',
                            autoclose: 2000
                        });
                        treeGrid.reload('ID', {
                            where: {}
                            ,page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                        jOrgChart()
                    });
                }else {
                    spop({
                        template: data.msg,
                        style: 'error',
                        autoclose: 2000
                    });
                }
            }
        });
    }

    /**
     * 更新
     * @param layer
     * @param body
     */
    function update(layer,body) {

        var id = body.contents().find("input[name=\"id\"]").val();
        var name = body.contents().find("input[name=\"name\"]").val();
        var pid = body.contents().find("#tree").val();
        var roles = body.contents().find("input[name=\"role\"]").val();

        $.ajax({
            url: "/department/update?roles="+roles,
            contentType: "application/json",
            type: "PUT",
            data:JSON.stringify({
                id:id,
                name:name,
                pid:pid
            }),
            dataType: "json",
            success: function(data){
                if(data.code==200){
                    //同步更新表格和缓存对应的值
                    layui.use(['jquery', 'layer'], function (){
                        layer.closeAll();
                        spop({
                            template: '更新成功',
                            style: 'success',
                            autoclose: 2000
                        });
                        treeGrid.reload('ID', {
                            where: {}
                            ,page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                        jOrgChart()
                    });
                }else {
                    spop({
                        template: data.msg,
                        style: 'error',
                        autoclose: 2000
                    });
                }
            }
        });
    }

    //组织结构 start

    $(function () {
        jOrgChart()
    })

    function jOrgChart(){
        $('#jOrgChart').html("");
        $.ajax({
            url:'/department/getAllDepartment',
            type:"GET",
            dataType: 'JSON',
            success:function(result){
                var showlist = $("<ul id='org' style='display:none'></ul>");
                showall(result, showlist);
                $("#jOrgChart").append(showlist);
                $("#org").jOrgChart( {
                    chartElement : '#jOrgChart'//指定在某个dom生成jorgchart
                });
            },
            error:function(e){
                var msg = e.msg;
                spop({
                    template: msg,
                    style: 'error',
                    autoclose: 2000
                });
            }
        });
    }

    function showall(data, parent) {

        $.each(data, function(index, val) {
            if(val.children != 'undefined'){

                var li = $("<li></li>");

                li.append("<a href='javascript:void(0)' onclick=getOrgId("+val.id+");>"+val.name+"</a>").append("<ul></ul>").appendTo(parent);
                //递归显示
                showall(val.children, $(li).children().eq(1));
            }else{
                $("<li></li>").append("<a href='javascript:void(0)' onclick=getOrgId("+val.id+");>"+val.name+"</a>").appendTo(parent);
            }
        });
    }

    // end
</script>
